package com.tanhao.takeaway.filter;

import com.alibaba.fastjson.JSON;
import com.tanhao.takeaway.commom.BaseContext;
import com.tanhao.takeaway.commom.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        System.setProperty("druid.mysql.usePingMethod","true");
        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse=(HttpServletResponse) servletResponse;
//        filterChain.doFilter(httpServletRequest,httpServletResponse);
        log.info("过滤了"+httpServletRequest.getRequestURI());
        String []s=new String[]{
                "/employee/login","/employee/logout","/backend/**","/front/**","/common/**","/user/sendMsg",
                "/user/login"
        };
       String url= httpServletRequest.getRequestURI();
       boolean check=check(url,s);
       if(check){
           log.info("本次请求：{}，不需要处理"+httpServletRequest.getRequestURI());
           filterChain.doFilter(httpServletRequest,httpServletResponse);
           return;
       }

       if(httpServletRequest.getSession().getAttribute("employee")!=null){
           log.info(httpServletRequest.getSession().getAttribute("employee")+"已登录");
           Long id= (Long) httpServletRequest.getSession().getAttribute("employee");
           BaseContext.setThreadLocalId(id);
           filterChain.doFilter(httpServletRequest,httpServletResponse);

           return;
       }

        if(httpServletRequest.getSession().getAttribute("user")!=null){
            log.info(httpServletRequest.getSession().getAttribute("user")+"已登录");
            Long id= (Long) httpServletRequest.getSession().getAttribute("user");
            BaseContext.setThreadLocalId(id);
            filterChain.doFilter(httpServletRequest,httpServletResponse);

            return;
        }

           log.info("用户未登录，请先登录");
           httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
       return;



    }

    public boolean check(String uri,String[] s){
          for(String s1:s){
              boolean match = antPathMatcher.match(s1, uri);
              if(match)return true;
          }
          return false;
    }
}
